package com.soulgame.sms.pay;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import cn.cmgame.billing.api.BillingResult;
import cn.cmgame.billing.api.GameInterface;
import cn.cmgame.billing.api.GameInterface.GameExitCallback;
import cn.cmgame.billing.api.GameInterface.PropsType;

import com.soul.sdk.constants.ResultCode;
import com.soul.sdk.constants.UserMapKey;
import com.soul.sdk.plugin.pay.IPayCallBack;
import com.soul.sdk.plugin.pay.PayParams;
import com.soul.sdk.plugin.user.IExitListener;
import com.soul.sdk.plugin.user.UserProxy;
import com.soul.sdk.utils.SGDebug;
import com.soul.sdk.utils.json.KJSONObject;
import com.soulgame.sms.contant.PayType;
import com.soulgame.sms.pay.vo.VoMiguPayParams;
import com.soulgame.sms.pay.vo.VoPayParams;

/**
 * @author lch
 * @version Create time：2017-3-15
 * @类说明：移动咪咕支付
 */
public class MiGuPay extends SMSPay {
	private Activity mActivity;

	private VoMiguPayParams mVoMiguPayParams;

	@Override
	public String getPayType() {
		return PayType.MIGU;
	}

	@Override
	public VoPayParams getVoPayParams() {
		return mVoMiguPayParams;
	}

	@Override
	public void init(Activity pActivity, KJSONObject pSdkParamsJSON) {
		this.mActivity = pActivity;
		this.mVoMiguPayParams = new VoMiguPayParams(pSdkParamsJSON);
		try {
			// 初始化SDK，并完成自动登陆
			GameInterface.initializeApp(pActivity);
		} catch (Exception e) {
			e.printStackTrace();
			SGDebug.print_e(this, "migu init error = " + e);
		}
		// SDK 存在退出对话框，这里记录一下。
		UserProxy.getInstance().setHasExitDialog(true);
	}

	@Override
	public void pay(Activity pActivity, PayParams pPayParams, IPayCallBack pPayCallBack) {
		if (mActivity == null) {
			mActivity = pActivity;
		}

		String pProductId = pPayParams.getProductId();

		String billingIndex = mVoMiguPayParams.getPayCode(pProductId);
		// 每次付费的付费流水号（即可理解为交易订单号）,咪咕规定长度为 16
		String cpParam = pPayParams.getSdkOrderId();
		// GameInterface
		// .doBilling(pActivity, true, true, billingIndex, cpParam,
		// this.getMiguPayCallback(pPayParams, pPayCallBack));
		// 26006
		// 其中第二个参数，详见PropsType类的常量1：PropsType.ONCE_ONLY,强制计费点2：PropsType.NORMAL,普通计费点4：PropsType.RIGHTS,权益道具计费点需与游戏申报时的计费点类型保持一致
		GameInterface.doBilling(pActivity, PropsType.NORMAL, billingIndex, cpParam,
				this.getMiguPayCallback(pPayParams, pPayCallBack));
	}

	/**
	 * 咪咕支付回调接口
	 * 
	 * @param pPayCallBack
	 *            返回给游戏端的支付回调接口
	 * @return 咪咕支付回调接口
	 */
	private GameInterface.IPayCallback getMiguPayCallback(final PayParams pPayParams, final IPayCallBack pPayCallBack) {

		return new GameInterface.IPayCallback() {

			@Override
			public void onResult(int resultCode, String billingIndex, Object obj) {
				String result = "";
				switch (resultCode) {
				case BillingResult.SUCCESS:
					if ((BillingResult.EXTRA_SENDSMS_TIMEOUT + "").equals(obj.toString())) {
						result = "短信计费超时";
						if (pPayCallBack != null) {
							pPayCallBack.onFail(ResultCode.CODE_PAY_TIMEOUT, result, pPayParams);
						}
					} else {
						result = "购买道具：[" + billingIndex + "] 成功！";
						if (pPayCallBack != null) {
							pPayCallBack.onSuccess(ResultCode.CODE_PAY_SUCCESS, result, pPayParams);
						}
					}
					break;
				case BillingResult.FAILED:
					result = "购买道具：[" + billingIndex + "] 失败！";
					if (pPayCallBack != null) {
						pPayCallBack.onFail(ResultCode.CODE_PAY_FAIL, result, pPayParams);
					}
					break;
				default:
					result = "购买道具：[" + billingIndex + "] 取消！";
					if (pPayCallBack != null) {
						pPayCallBack.onFail(ResultCode.CODE_PAY_CANCEL, result, pPayParams);
					}
					break;
				}

			}

		};
	}

	@Override
	public void exit(final Activity pActivity, final Map<String, String> customParams, final IExitListener pExitListener) {
		if (mActivity == null) {
			mActivity = pActivity;
		}

		if (customParams != null) {
			if ("true".equalsIgnoreCase(customParams.get(UserMapKey.IS_CONTAIN_EXIT_DIALOG))) {
				// 有渠道SDK，已经存在了退出对话框
				this.showMiguExitDialog(customParams, pExitListener);
			} else {
				// 渠道不存在退出界面，弹出退出框
				this.showExitDialog(customParams, pExitListener);
			}
		} else {
			this.showExitDialog(customParams, pExitListener);
		}

	}

	private void showMiguExitDialog(final Map<String, String> customParams, final IExitListener pExitListener) {
		SGDebug.print_d(this, "showMiguExitDialog");
		GameInterface.exit(mActivity, new GameExitCallback() {

			@Override
			public void onConfirmExit() {
				// 此方法已经包含延迟退出处理,能执行下面的方法，但即使我们不作退出操作，它这里也会退出游戏
				SGDebug.print_v(this, "showMiguExitDialog onConfirmExit");
				// 回调退出点击事件
				exitCallback(customParams, pExitListener);
			}

			@Override
			public void onCancelExit() {
				SGDebug.print_v(this, "showMiguExitDialog onCancelExit");

			}
		});

	}

	private void exitCallback(final Map<String, String> customParams, final IExitListener pExitListener) {
		if (pExitListener != null) {

			Map<String, String> mExitMap = null;
			if (customParams != null) {
				mExitMap = customParams;
			} else {
				mExitMap = new HashMap<String, String>();
			}
			// 标记已有退出框
			mExitMap.put(UserMapKey.IS_CONTAIN_EXIT_DIALOG, "true");

			pExitListener.onExit(mExitMap);
		}
	}

	private void showExitDialog(final Map<String, String> customParams, final IExitListener pExitListener) {

		PackageManager pm = mActivity.getPackageManager();
		String appName = mActivity.getApplicationInfo().loadLabel(pm).toString();
		Builder builder = new Builder(mActivity);
		if (appName != null) {
			builder.setTitle(appName);
		}
		builder.setMessage("确定退出游戏？");
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// 咪咕退出对话框
				showMiguExitDialog(customParams, pExitListener);
			}
		});
		builder.setNegativeButton("取消", null).show();

	}

	/**
	 * migu 技术给的秘密武器,解决在activity中加载so文件时退出游戏后找不到 GameService 的情况
	 * 获取Service的Intent
	 * 
	 * @param {[type]} Context mContext [description]
	 * @param {[type]} String className [description]
	 * @return {Boolean} [description]
	 */
	public static Intent isServiceRunning(Context mContext, String className) {
		Intent serviceIntent = null;

		try {
			ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
			List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(50);
			if (!(serviceList.size() > 0)) {
				return null;
			}
			for (int i = 0; i < serviceList.size(); i++) {
				if (serviceList.get(i).service.getClassName().equals(className) == true) {
					serviceIntent = new Intent();
					serviceIntent.setComponent(serviceList.get(i).service);
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return serviceIntent;
	}

	@Override
	public void onDestroy() {
		// 要确保此方法在退出程序前有调用
		SGDebug.print_w(this, "onDestroy()");
		Intent serviceIntent = isServiceRunning(mActivity, "cn.cmgame.billing.service.GameService");
		if (null != serviceIntent) {
			SGDebug.print_w("GameService isRunning,stop it!");
			boolean isSucc = mActivity.stopService(serviceIntent);
			SGDebug.print_d("GameService is stop succ? = " + isSucc);
		} else {
			SGDebug.print_w("GameService do not running!");
		}
	}

}
